<template>
  <n-layout class="index-container" has-sider position="absolute">

    <n-drawer v-model:show="chatState.showChatSiderDrawer" :width="260" class="menu-drawer" placement="left"
      to=".index-container" display-directive="show">
      <n-drawer-content>
        <n-layout-sider :native-scrollbar="false" :width="260">
          <ChatSider :msgList="chatState.msgList" :listLoading="chatState.listLoading" @delChat="delChat"
            @openNewChat="openNewChat" @changeChat="changeChat" @openLogin="openLoginSignup"
            @openWechatOfficial="openWechatOfficial" />
        </n-layout-sider>
      </n-drawer-content>
    </n-drawer>

    <n-layout-sider :native-scrollbar="false" :width="260" class="xs:hidden m:flex">
      <ChatSider :msgList="chatState.msgList" :listLoading="chatState.listLoading" @delChat="delChat"
        @openNewChat="openNewChat" @changeChat="changeChat" @openLogin="openLoginSignup"
        @openWechatOfficial="openWechatOfficial" />
    </n-layout-sider>

    <n-layout :native-scrollbar="false" class="main-layout">
      <n-layout-header
        class="sticky top-0 z-10 bg-dark border-b border-white/20 items-center justify-between h-11 px-3 xs:flex m:hidden">
        <n-button :focusable="false" class="text-[#d9d9e3] hover:text-[#b1b1b1]" text
          @click="chatState.showChatSiderDrawer = true">
          <n-icon :component="MenuOutline" color="#d9d9e3" size="26" />
        </n-button>
        <n-ellipsis class="max-w-60 text-[#d9d9e3] px-8">
          {{ chatState.title }}
        </n-ellipsis>
        <n-button :focusable="false" class="text-[#d9d9e3] hover:text-[#b1b1b1]" text @click="openNewChat">
          <n-icon :component="AddOutline" size="26" />
        </n-button>
      </n-layout-header>
      <n-layout-content class="main-content mb-0 dark:bg-dark">
        <div class="content-container m:px-6 pb-10 xs:h-[calc(100vh-44px)] m:h-screen my-0 mx-auto"
          v-if="chatState.isNewChat">
          <div class="flex flex-col justify-between">
            <div class="w-full overflow-auto px-3 xs:h-[calc(100vh-192px)]">
              <n-h1 class="text-center font-semibold xs:mt-0 s:mt-[18vh] mb-10">智能对话机器人</n-h1>
              <n-grid x-gap="15" y-gap="15" cols="xs:1 s:3" responsive="screen">
                <n-gi class="text-center" v-for="item in unref(chatState.gridData)" :key="item.title">
                  <n-text class="text-lg">{{ item.title }}</n-text>
                  <n-space class="mt-4" vertical :size="15">
                    <div v-for="text in item.data" :key="text" @click="item.isLink ? changeMsg(text) : ''" :class="['rounded', 'p-3', 'bg-[#F7F7F8]', 'dark:bg-[#3E3F4B]', { 'cursor-pointer': item.isLink },
                      { 'hover:bg-[#D9D9E3]': item.isLink }, { 'dark:hover:bg-[#202123]': item.isLink }]">
                      {{ text }}
                    </div>
                  </n-space>
                </n-gi>
              </n-grid>
            </div>
            <ChatInput ref="chatInputRef" @sendMsg="sendMsg" @changeMsg="changeMsg" />
          </div>
        </div>
        <router-view @openNewChat="openNewChat" @addChat="addChat" :message="chatState.message" v-else />
      </n-layout-content>
    </n-layout>
  </n-layout>

  <LoginRegister ref="loginSignupRef" @getMsgList="getMsgList" />
  <WechatOfficial ref="wechatOfficialRef" />
</template>

<script setup>
import { reactive, unref, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore, useMainStore } from '@/store'
import { messageList, deleteMessage } from '@api/chatApi'
import { AddOutline, MenuOutline } from '@vicons/ionicons5'
import { useDialog } from '@/hook/popup/useDialog'
import WechatOfficial from './components/WechatOfficial.vue'
import ChatInput from './components/ChatInput.vue'
import ChatSider from './components/ChatSider.vue'
import LoginRegister from './components/LoginRegister.vue'

const mainStore = useMainStore()
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

const chatState = reactive({
  isNewChat: null,
  showChatSiderDrawer: false,
  listLoading: false,
  msgList: [],
  title: '',
  message: '',
  gridData: [
    {
      title: '例子',
      isLink: true,
      data: ['"用简单的术语解释量子计算“→', '"对一个10岁的生日有什么创意吗？“→', '"如何在 Javascript 中发出 HTTP 请求？“→']
    },
    {
      title: '能力',
      isLink: false,
      data: ['记住用户之前在对话中所说的话', '允许用户提供后续更正', '接受过拒绝不当请求的培训']
    },
    {
      title: '局限性',
      isLink: false,
      data: ['可能偶尔生成不正确的信息', '可能偶尔产生有害说明或有偏见的内容', '对2021年后的世界和事件的了解有限']
    }
  ],
})

if (route.params.id === 'new') {
  chatState.isNewChat = true
  chatState.title = '新对话窗口'
  mainStore.setDocTitle(chatState.title)
}

const getMsgList = async () => {
  if (userStore.isLogin) {
    try {
      chatState.listLoading = true
      const res = await messageList()
      if (res.statusCode === 200) {
        chatState.msgList = res.data
        res.data.forEach(item => {
          if (route.params.id === item.conversationId) {
            chatState.title = item.title
            mainStore.setDocTitle(item.title)
          }
        })
      }
    } finally {
      chatState.listLoading = false
    }
  }
}
getMsgList()

const openWechatOfficial = () => {
  proxy.$refs.wechatOfficialRef.basicOpenWxModal()
}

const openLoginSignup = () => {
  proxy.$refs.loginSignupRef.openLogin()
}

const changeMsg = (msg) => {
  chatState.message = msg
  proxy.$refs.chatInputRef?.changeMsg(msg)
}

const addChat = (chat) => {
  chatState.msgList.unshift(chat)
}

const sendMsg = () => {
  if (chatState.message) {
    chatState.isNewChat = false
  }
}

const openNewChat = () => {
  chatState.title = '新对话窗口'
  mainStore.setDocTitle(chatState.title)
  chatState.isNewChat = true
  chatState.showChatSiderDrawer = false
  chatState.message = ''
  router.push('/chat/new')
}

const changeChat = (item) => {
  chatState.title = item.title
  mainStore.setDocTitle(item.title)
  chatState.showChatSiderDrawer = false
  chatState.isNewChat = false
  changeMsg('')
  router.push(`/chat/${item.conversationId}`)
}

const delChat = (id) => {
  const delDialog = useDialog({
    title: '删除',
    content: '是否删除该会话？',
    type: 'error',
    icon: true,
    async confirm() {
      const res = await deleteMessage({ conversationId: [id] })
      if (res?.statusCode === 200) {
        delDialog.destroy()
        await openNewChat()
        chatState.msgList.forEach((item, index) => {
          if (item.conversationId === id) {
            chatState.msgList.splice(index, 1)
          }
        })
        $message.success(res.message, {
          duration: 1500
        })
      }
    },
  })
}
</script>

<style lang="less" scoped>
.index-container {

  &:deep(.menu-drawer) {
    .n-drawer-body {
      .n-drawer-body-content-wrapper {
        padding: 0;
      }
    }
  }

  &:deep(.n-layout-sider) {
    background-color: #202123;

    .newchat-box {
      .n-button--ghost {

        .n-button__state-border,
        .n-button__border {
          border-color: #55575e;
        }
      }

      .n-button:not(.n-button--disabled):hover {
        background-color: #2B2C2F;
      }
    }

    .option-space {
      border-top: 1px solid #55575e;

      .chat-block {
        .n-button {
          .n-button__content {
            width: 100%;

            .n-icon {
              visibility: hidden;
            }
          }
        }
      }

      .n-button {
        width: 100%;
        height: 44px;
        color: #ececf1;
        justify-content: flex-start;

        .n-button__icon {
          font-size: 22px;
          margin-right: 15px;
          margin-top: 3px;
        }
      }

      .n-button:not(.n-button--disabled):hover {
        background-color: #2A2B32;
      }
    }
  }

  &:deep(.main-layout) {
    .n-scrollbar-content {
      .main-content {
        background-color: #fff;

        .n-layout-scroll-container {
          width: 100%;

          .content-container {
            max-width: 848px;
            padding-top: 44px;
          }

          .n-input {
            .n-input__input-el {
              height: 48px;
            }

            .n-input__state-border {
              display: none;
            }

            .n-input__suffix {
              .n-button {
                transform: rotate(-35deg);
                margin-top: -2px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
